在說到繼承、介面、和多型之前,我們要先知道Java修飾子的存取
public: 所有地方都可以存取
private: 只能在當前類別存取
protected: 可以在同一package和子類別存取
final: 屬性和方法不可以被覆寫
static: 屬性和方法屬於類別,不是屬於使用物件
abstract: 只用在抽象類別中,而且只能用在方法上(抽象類別在之後會介紹)
繼承就是說可以把某個類別(父類別)的屬性和方法繼承到另一個類別(子類別)
像是我們有個父類別是Animal,他有很多子類別,像是Dog, Cat, mouse, ...
// Main.java
public class Main {
public static void main(String[] args){
Cat cat = new Cat("Steph", 5);
cat.eat();
cat.sleep();
cat.meow();
}
}
// Animal.java
public class Animal {
protected String name;
protected int age;
// method overloading
public Animal(){
this.name = "A animal";
this.age = 0;
}
public Animal(String name, int age){
this.name = name;
this.age = age;
}
public void eat(){
System.out.println("Eatting...");
}
public void sleep(){
System.out.println("Sleeping...");
}
}
// Cat.java
public class Cat {
public Cat(String name, int age){
this.name = name;
this.age = age;
}
public void meow(){
System.out.println("Meow...");
}
}
// Main.java
public class Main {
public static void main(String[] args){
Animal dog = new Dog();
Cat cat1 = new Cat();
Animal cat2 = new Cat();
// Animal animal = new Animal(); //'Animal' is abstract; cannot be instantiated
// Polymorphism => 生態多樣性的概念
// 同一個Animal物件可以有Dog,Cat...各種可能性
dog1.makeSound();
cat1.makeSound();
cat2.makeSound();
}
}
// Animal.java
public abstract class Animal {
protected String name;
protected int age;
// method overloading
public Animal(){
this.name = "A animal";
this.age = 0;
}
public Animal(String name, int age){
this.name = name;
this.age = age;
}
public void eat(){
System.out.println("Eatting...");
}
public void sleep(){
System.out.println("Sleeping...");
}
public abstract void makeSound();
}
// Cat.java
public class Cat extends Animal{
public Cat(){
super("Cat"); // super: 讓Cat(子類別)呼叫Animal(父類別)的建構子
}
@Override
public void makeSound(){
System.out.println("Meow...");
}
}
// Dog.java
public class Dog extends Animal{
public Dog(){
super("Dog");
}
@Override
public void makeSound(){
System.out.println("Bark...");
}
}